package com.knife.tools;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import com.knife.news.logic.PicService;
import com.knife.news.logic.SiteService;
import com.knife.news.logic.impl.PicServiceImpl;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.model.Pic;
import com.knife.news.object.Site;
import com.knife.util.CommUtil;
import com.knife.web.Globals;

public class ImageUpload extends HttpServlet {
	private static final long serialVersionUID = -7825355637448948879L;
	private SiteService siteDAO = new SiteServiceImpl();
	private PicService picDAO=PicServiceImpl.getInstance();
	private String base;
	private String filext="";

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存缓冲区，超过后写入临时文件
		factory.setSizeThreshold(10240000);
		// 设置临时文件存储位置
		base = Globals.APP_BASE_DIR + File.separator + "html" + File.separator;
		File file = new File(base);
		if (!file.exists())
			file.mkdirs();
		factory.setRepository(file);
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置单个文件的最大上传值
		upload.setFileSizeMax(10002400000l);
		// 设置整个request的最大值
		upload.setSizeMax(10002400000l);
		upload.setHeaderEncoding("UTF-8");
		try {
        	String sid = CommUtil.null2String(request.getParameter("sid"));
        	String pid = CommUtil.null2String(request.getParameter("pid"));
        	int userid = CommUtil.null2Int(request.getParameter("uid"));
			Site site = new Site();
			if(sid.length()>0){
				site = siteDAO.getSiteById(sid);
			}else{
				site = siteDAO.getSite();
			}
			
			List<?> items = upload.parseRequest(request);
			FileItem item = null;
			String fileName = null;
			String sfileName = null;
			String newsid = CommUtil.null2String(request.getParameter("newsid"));
			int spic	= CommUtil.null2Int(request.getParameter("spic"));
			int swidth	= CommUtil.null2Int(request.getParameter("swidth"));
			int sheight	= CommUtil.null2Int(request.getParameter("sheight"));
			for (int i = 0; i < items.size(); i++) {
				item = (FileItem) items.get(i);
				String name = item.getName();
                long size = item.getSize();
                if ((name == null || name.equals("")) && size == 0) {
                    continue;
                }
				
				filext = FilenameUtils.getExtension(name);
				if(filext!=null){
					if(filext.trim().length()<=0){
						if(name.lastIndexOf(".")>0){
							filext=name.substring(name.lastIndexOf(".")+1,name.length());
						}
					}
				}
				UUID uid = UUID.randomUUID();
				String newfilename = uid.toString()+ ".jpg";
				if(filext!=null){
					newfilename = uid.toString() + "." + filext.toLowerCase();
				}
				fileName = Globals.APP_BASE_DIR + File.separator + "html" + File.separator + site.getPub_dir() + File.separator + "upload"+File.separator+"images" + File.separator + Calendar.getInstance().get(Calendar.YEAR) + File.separator
                + (Calendar.getInstance().get(Calendar.MONTH)+1) + File.separator + newfilename;
				sfileName = Globals.APP_BASE_DIR + File.separator + "html" + File.separator + site.getPub_dir() + File.separator + "upload"+File.separator+"images" + File.separator + Calendar.getInstance().get(Calendar.YEAR) + File.separator
                + (Calendar.getInstance().get(Calendar.MONTH)+1) + File.separator + "s_" +newfilename;
				
				String pubPath = Globals.APP_BASE_DIR + File.separator + "wwwroot" + File.separator + site.getPub_dir() + File.separator + "upload"+ File.separator +"images" + File.separator + Calendar.getInstance().get(Calendar.YEAR) + File.separator
                        + (Calendar.getInstance().get(Calendar.MONTH)+1) + File.separator + newfilename;
				String spubPath = Globals.APP_BASE_DIR + File.separator + "wwwroot" + File.separator + site.getPub_dir() + File.separator + "upload"+File.separator+"images" + File.separator + Calendar.getInstance().get(Calendar.YEAR) + File.separator
		                + (Calendar.getInstance().get(Calendar.MONTH)+1) + File.separator + "s_" +newfilename;
				File realfile = new File(fileName);
			    if (!(realfile.getParentFile().exists())){
			    	realfile.getParentFile().mkdirs();
			    }
				// 保存文件
				if (!item.isFormField() && item.getName().length() > 0) {
					item.write(realfile);
					if(site.getHtml()==1){
						CopyDirectory.copyFile(realfile, new File(pubPath));
						if(site.getBig5()==1){
							String big5Path = fileName.replace(site.getPub_dir() + File.separator + "upload", site.getPub_dir() + File.separator + "big5"+File.separator+"upload");
							CopyDirectory.copyFile(realfile, new File(big5Path));
							String big5PubPath = pubPath.replace(site.getPub_dir() + File.separator + "upload", site.getPub_dir() + File.separator + "big5"+File.separator+"upload");
							CopyDirectory.copyFile(realfile, new File(big5PubPath));
						}
					}
					//生成缩略图
					if(spic>0){
						File spicFile=new File(sfileName);
						//Thumbnails.of(realfile).size(swidth, sheight).keepAspectRatio(false).outputQuality(1.0f).toFile(spicFile);
						Thumbnails.of(realfile).size(swidth, sheight).keepAspectRatio(false).toFile(spicFile);
						if(site.getHtml()==1){
							CopyDirectory.copyFile(spicFile, new File(spubPath));
						}
					}
					// 记录到数据库
					String pic_url = "/html/"+site.getPub_dir()+"/upload/images/" + Calendar.getInstance().get(Calendar.YEAR) + "/" + (Calendar.getInstance().get(Calendar.MONTH)+1) + "/" + newfilename;
					Pic apic = new Pic();
					apic.setNewsid(newsid);
					apic.setPictype(pid);
					apic.setUserid(userid);
					apic.setUrl(pic_url);
					apic.setDisplay(0);
					com.knife.news.object.Pic bpic=new com.knife.news.object.Pic(apic);
					if(picDAO.savePic(bpic)){
						PrintWriter out = response.getWriter();
						out.print("PICID:" + apic.getId());
						out.print(":PICURL:" + pic_url);
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("rawtypes")
	public String getParameterValue(HttpServletRequest request, String paramName) {
		String result="";
		try {
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (isMultipart == true) {
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				List fileItemList = upload.parseRequest(request);
				if (fileItemList != null) {
					for (Iterator itr = fileItemList.iterator(); itr.hasNext();) {
						FileItem fileItem = (FileItem) itr.next();
						if (fileItem.getFieldName().equalsIgnoreCase(paramName)) {
							result=new String(fileItem.getString().getBytes(
									"ISO8859-1"));// 中文转码
						}
					}
				}
			} else {
				result=new String(request.getParameter(paramName).getBytes(
						"ISO8859-1"));// 中文转码
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
